import axios1 from 'axios'
import store from '@/store'
import to from '@/utils/awaitTo'
import Notify from '@/ui/Notify'
import router from '@/router'
import { removeStorage } from '@/storage'
var JSONbigString = require('json-bigint')({ storeAsString: true })
// axios.defaults.baseURL = 'http://toutiao-app.itheima.net'
const axios = axios1.create({
  baseURL: 'http://toutiao-app.itheima.net',
  transformResponse: [function (data) {
    // 对 data 进行任意转换处理
    return JSONbigString.parse(data)
  }]
})

// 添加请求拦截器
axios.interceptors.request.use(function (config) {
  if (store.state.token) {
    config.headers.Authorization = 'Bearer ' + store.state.token
  }

  // 在发送请求之前做些什么
  return config
}, function (error) {
  // 对请求错误做些什么
  return Promise.reject(error)
})

// 添加响应拦截器
axios.interceptors.response.use(function (response) {
  // 对响应数据做点什么
  return response
}, function (error) {
  // 对响应错误做点什么
  if (error.response.status === 401) {
    Notify({ type: 'danger', message: 'token过期_请重新登录' })
    removeStorage('token')
    store.commit('clearToken')
    setTimeout(() => {
      router.push({
        name: 'Login'
      })
    }, 1000)
  }
  return Promise.reject(error)
})
export default ({ url, method = 'GET', data = {}, headers = {}, params = {} }) => {
  return to(axios({
    url,
    method,
    data,
    headers,
    params
  }))
}
